﻿var options, desktopNotification;

function showDesktopNotification(title, text, url) {
	desktopNotification = webkitNotifications.createNotification('images/icon32.png', title, text);
	desktopNotification.onclick = function() {
		desktopNotification.cancel();
		chrome.browserAction.setBadgeText({'text': ''});
		chrome.tabs.create({'url': url});
	}
	desktopNotification.show();
	window.setTimeout('desktopNotification.cancel()', 10000);
}

function notifierPoll() {
	getNotifications(function(list) {
		var links = list.getElementsByTagName('a');
		if (links.length == 0) { return; }
		
		var	link = links[0],
			strNotif = link.firstChild.textContent.trim(),
			notifTime = list.querySelector('span').textContent;
		if (options.desktopNotifications && link.getAttribute('class') == 'new' && notifTime > localStorage.lastNotification) {
			showDesktopNotification(
				strNotif, 
				humanize_time(notifTime),
				'http://www.fitocracy.com' + link.getAttribute('href'));
			localStorage.lastNotification = notifTime;
		}
		var nbNotif = 0;
		for (var i = 0; i < links.length; i++) {
			if (links[i].getAttribute('class') == 'new')
				nbNotif++;
		}
		chrome.browserAction.setBadgeText({'text': (nbNotif > 0 ? nbNotif.toString() : '')});
	});
}

function onRequest(request, sender, callback) {		
	switch(request.type) {	
		case 'getOptions':	
			options = loadOptions();
			callback(options);
			break;
		case 'saveJSON':	
			saveJSON(request.name, request.value);	
			break;
		case 'loadJSON':	
			callback(loadJSON(request.name));
			break;
		break;
	}
}

function init() {
	chrome.extension.onRequest.addListener(onRequest);
	options = loadOptions();
	if (options.notifierEnabled) {
		notifierPoll();
		window.setInterval(notifierPoll, 60*1000);
	}
}		

init();